// iOS权限修复代码示例
// 此文件展示如何正确地在iOS上请求权限

import 'dart:async';
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

/// iOS权限修复版本的权限服务
/// 
/// 核心改进：
/// 1. 不在应用启动时批量请求权限
/// 2. 按需请求权限，在用户交互后立即请求
/// 3. 添加权限请求的上下文说明
/// 4. 实现渐进式权限请求策略
class PermissionServiceFixed extends GetxService {
  
  // 权限状态
  final RxBool _locationPermissionGranted = false.obs;
  final RxBool _microphonePermissionGranted = false.obs;
  final RxBool _notificationPermissionGranted = false.obs;
  
  // 防止重复请求的标志
  bool _isRequestingLocationPermission = false;
  bool _isRequestingMicrophonePermission = false;
  bool _isRequestingNotificationPermission = false;

  // 获取权限状态
  bool get isLocationPermissionGranted => _locationPermissionGranted.value;
  bool get isMicrophonePermissionGranted => _microphonePermissionGranted.value;
  bool get isNotificationPermissionGranted => _notificationPermissionGranted.value;

  @override
  void onInit() {
    super.onInit();
    developer.log('PermissionServiceFixed onInit');
    
    // ❌ 不要在初始化时请求权限
    // requestAllPermissions(); // 删除这种做法
    
    // ✅ 只检查权限状态，不请求权限
    _checkCurrentPermissionStatus();
  }

  // 🔍 检查当前权限状态（不请求权限）
  Future<void> _checkCurrentPermissionStatus() async {
    try {
      final locationStatus = await Permission.location.status;
      final microphoneStatus = await Permission.microphone.status;
      final notificationStatus = await Permission.notification.status;
      
      _locationPermissionGranted.value = locationStatus.isGranted;
      _microphonePermissionGranted.value = microphoneStatus.isGranted;
      _notificationPermissionGranted.value = notificationStatus.isGranted;
      
      developer.log('📋 当前权限状态（仅检查）:');
      developer.log('📍 位置权限: $locationStatus');
      developer.log('🎤 麦克风权限: $microphoneStatus');
      developer.log('🔔 通知权限: $notificationStatus');
      
    } catch (e) {
      developer.log('💥 权限状态检查异常: $e');
    }
  }

  // 🗺️ 按需请求位置权限（用户点击位置功能时调用）
  Future<bool> requestLocationPermissionOnDemand({
    required String reason,
    required VoidCallback onGranted,
    required VoidCallback onDenied,
  }) async {
    developer.log('🔐 =============== 按需请求位置权限 ===============');
    developer.log('📍 请求原因: $reason');
    
    if (_isRequestingLocationPermission) {
      developer.log('⚠️ 正在请求位置权限中，跳过重复请求');
      return _locationPermissionGranted.value;
    }

    // 首先显示权限说明对话框
    final userAgreed = await _showPermissionExplanationDialog(
      title: '需要位置权限',
      message: reason,
      icon: Icons.location_on,
    );

    if (!userAgreed) {
      developer.log('❌ 用户拒绝了权限说明，取消权限请求');
      onDenied();
      return false;
    }

    _isRequestingLocationPermission = true;
    try {
      final permission = Permission.location;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前位置权限状态: $status');
      
      if (status.isGranted) {
        developer.log('✅ 位置权限已授予');
        _locationPermissionGranted.value = true;
        onGranted();
        return true;
      }
      
      if (status.isPermanentlyDenied) {
        developer.log('🚫 位置权限被永久拒绝，引导用户到设置');
        _showGoToSettingsDialog('位置权限');
        onDenied();
        return false;
      }
      
      // 请求权限（此时应该弹出系统对话框）
      developer.log('📲 正在请求位置权限...');
      status = await permission.request();
      developer.log('📋 位置权限请求结果: $status');
      
      if (status.isGranted) {
        developer.log('✅ 位置权限请求成功');
        _locationPermissionGranted.value = true;
        onGranted();
        return true;
      } else {
        developer.log('❌ 位置权限请求失败: $status');
        _locationPermissionGranted.value = false;
        onDenied();
        return false;
      }
      
    } catch (e) {
      developer.log('💥 请求位置权限异常: $e');
      _locationPermissionGranted.value = false;
      onDenied();
      return false;
    } finally {
      _isRequestingLocationPermission = false;
      developer.log('🏁 =============== 位置权限请求结束 ===============');
    }
  }

  // 🎤 按需请求麦克风权限（用户点击语音功能时调用）
  Future<bool> requestMicrophonePermissionOnDemand({
    required String reason,
    required VoidCallback onGranted,
    required VoidCallback onDenied,
  }) async {
    developer.log('🔐 =============== 按需请求麦克风权限 ===============');
    developer.log('🎤 请求原因: $reason');
    
    if (_isRequestingMicrophonePermission) {
      developer.log('⚠️ 正在请求麦克风权限中，跳过重复请求');
      return _microphonePermissionGranted.value;
    }

    // 首先显示权限说明对话框
    final userAgreed = await _showPermissionExplanationDialog(
      title: '需要麦克风权限',
      message: reason,
      icon: Icons.mic,
    );

    if (!userAgreed) {
      developer.log('❌ 用户拒绝了权限说明，取消权限请求');
      onDenied();
      return false;
    }

    _isRequestingMicrophonePermission = true;
    try {
      final permission = Permission.microphone;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前麦克风权限状态: $status');
      
      if (status.isGranted) {
        developer.log('✅ 麦克风权限已授予');
        _microphonePermissionGranted.value = true;
        onGranted();
        return true;
      }
      
      if (status.isPermanentlyDenied) {
        developer.log('🚫 麦克风权限被永久拒绝，引导用户到设置');
        _showGoToSettingsDialog('麦克风权限');
        onDenied();
        return false;
      }
      
      // 请求权限（此时应该弹出系统对话框）
      developer.log('📲 正在请求麦克风权限...');
      status = await permission.request();
      developer.log('📋 麦克风权限请求结果: $status');
      
      if (status.isGranted) {
        developer.log('✅ 麦克风权限请求成功');
        _microphonePermissionGranted.value = true;
        onGranted();
        return true;
      } else {
        developer.log('❌ 麦克风权限请求失败: $status');
        _microphonePermissionGranted.value = false;
        onDenied();
        return false;
      }
      
    } catch (e) {
      developer.log('💥 请求麦克风权限异常: $e');
      _microphonePermissionGranted.value = false;
      onDenied();
      return false;
    } finally {
      _isRequestingMicrophonePermission = false;
      developer.log('🏁 =============== 麦克风权限请求结束 ===============');
    }
  }

  // 🔔 按需请求通知权限（用户在设置中开启通知时调用）
  Future<bool> requestNotificationPermissionOnDemand({
    required String reason,
    required VoidCallback onGranted,
    required VoidCallback onDenied,
  }) async {
    developer.log('🔐 =============== 按需请求通知权限 ===============');
    developer.log('🔔 请求原因: $reason');
    
    if (_isRequestingNotificationPermission) {
      developer.log('⚠️ 正在请求通知权限中，跳过重复请求');
      return _notificationPermissionGranted.value;
    }

    // 首先显示权限说明对话框
    final userAgreed = await _showPermissionExplanationDialog(
      title: '需要通知权限',
      message: reason,
      icon: Icons.notifications,
    );

    if (!userAgreed) {
      developer.log('❌ 用户拒绝了权限说明，取消权限请求');
      onDenied();
      return false;
    }

    _isRequestingNotificationPermission = true;
    try {
      final permission = Permission.notification;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前通知权限状态: $status');
      
      if (status.isGranted) {
        developer.log('✅ 通知权限已授予');
        _notificationPermissionGranted.value = true;
        onGranted();
        return true;
      }
      
      if (status.isPermanentlyDenied) {
        developer.log('🚫 通知权限被永久拒绝，引导用户到设置');
        _showGoToSettingsDialog('通知权限');
        onDenied();
        return false;
      }
      
      // 请求权限（此时应该弹出系统对话框）
      developer.log('📲 正在请求通知权限...');
      status = await permission.request();
      developer.log('📋 通知权限请求结果: $status');
      
      if (status.isGranted) {
        developer.log('✅ 通知权限请求成功');
        _notificationPermissionGranted.value = true;
        onGranted();
        return true;
      } else {
        developer.log('❌ 通知权限请求失败: $status');
        _notificationPermissionGranted.value = false;
        onDenied();
        return false;
      }
      
    } catch (e) {
      developer.log('💥 请求通知权限异常: $e');
      _notificationPermissionGranted.value = false;
      onDenied();
      return false;
    } finally {
      _isRequestingNotificationPermission = false;
      developer.log('🏁 =============== 通知权限请求结束 ===============');
    }
  }

  // 显示权限说明对话框
  Future<bool> _showPermissionExplanationDialog({
    required String title,
    required String message,
    required IconData icon,
  }) async {
    final completer = Completer<bool>();
    
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, size: 48, color: Colors.blue),
              const SizedBox(height: 16),
              Text(
                title,
                style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              Text(
                message,
                style: const TextStyle(fontSize: 14),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 20),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () {
                        Get.back();
                        completer.complete(false);
                      },
                      child: const Text('取消'),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        Get.back();
                        completer.complete(true);
                      },
                      child: const Text('同意'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );
    
    return completer.future;
  }

  // 显示引导用户到设置的对话框
  Future<void> _showGoToSettingsDialog(String permissionName) async {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.settings, size: 48, color: Colors.orange),
              const SizedBox(height: 16),
              Text(
                '需要手动开启$permissionName',
                style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              Text(
                '$permissionName已被拒绝，请前往设置页面手动开启',
                style: const TextStyle(fontSize: 14),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 20),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(),
                      child: const Text('取消'),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        Get.back();
                        openAppSettings();
                      },
                      child: const Text('去设置'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 使用示例：
// 
// 在需要位置权限的地方：
// final permissionService = Get.find<PermissionServiceFixed>();
// permissionService.requestLocationPermissionOnDemand(
//   reason: '我们需要您的位置来推荐附近的活动',
//   onGranted: () {
//     // 权限获得后的操作
//     startLocationService();
//   },
//   onDenied: () {
//     // 权限被拒绝后的操作
//     showLocationDisabledMessage();
//   },
// );
//
// 在需要麦克风权限的地方：
// permissionService.requestMicrophonePermissionOnDemand(
//   reason: '录制语音消息需要使用您的麦克风',
//   onGranted: () {
//     startRecording();
//   },
//   onDenied: () {
//     showMicrophoneDisabledMessage();
//   },
// );
//
// 在通知设置页面：
// permissionService.requestNotificationPermissionOnDemand(
//   reason: '开启通知后可以及时收到消息提醒',
//   onGranted: () {
//     enableNotifications();
//   },
//   onDenied: () {
//     showNotificationDisabledMessage();
//   },
// );
